'use client';

import { useState } from 'react';
import { useWriteContract } from 'wagmi';
import { parseUnits } from 'viem';
//import erc20Abi from '../abi/erc20Abi.json';
import MockUSDC_ABI from '../abis/MockUSDC.json';
import MiniVault_ABI from '../abis/MiniVault.json';
import contractAddresses from '../constants/contracts.json'; // 自动生成的地址

const USDC_ADDRESS = contractAddresses.MockUSDC;
const VAULT_ADDRESS = contractAddresses.MiniVault;

export function ApproveButton() {
  const [amount, setAmount] = useState('');
  const [submitted, setSubmitted] = useState(false);

  const { writeContract, isPending, isSuccess, error } = useWriteContract();

  const handleApprove = () => {
    if (!amount) return;

    writeContract({
      address: USDC_ADDRESS as `0x${string}`,
      abi: MockUSDC_ABI.abi,
      functionName: 'approve',
      args: [VAULT_ADDRESS, parseUnits(amount, 6)],
    });

    setSubmitted(true);
  };

  return (
    <div className="space-y-2">
      <input
        type="number"
        min="0"
        placeholder="Amount to Approve"
        value={amount}
        onChange={(e) => setAmount(e.target.value)}
        className="w-full px-4 py-2 border border-gray-200 rounded-xl bg-gray-100 
        placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-400
        placeholder:text-sm placeholder:font-light text-black"
      />
      <button
        onClick={handleApprove}
        disabled={isPending || !amount}
        className="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 rounded-xl w-full"
      >
        {isPending ? 'Approving...' : 'Approve Vault'}
      </button>
      {isSuccess && submitted && <p className="text-green-600">Approved! {amount}</p>}
      {error && <p className="text-red-600">Error: {error.message}</p>}
    </div>
  );
}
